package fr.sedoo.commons.server.storedfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class TmpFileManager {

	private static HashMap<String, String> fileMap = new HashMap<String, String>();

	private static String PREFIX = "TMP_FILE_MANAGER";

	public static void removeTmpFile(String fileName) {
		String tmpFilePath = fileMap.get(fileName);
		fileMap.remove(fileName);
		FileUtils.deleteQuietly(new File(tmpFilePath));
	}

	/**
	 * We delete files uploaded more than two hours ago.
	 */
	private static void deleteOldEntries() {
		String currentPrefix = getCurrentHourPrefix();
		String previousPrefix = getPreviousHourPrefix();
		ArrayList<String> keyToDelete = new ArrayList<String>();
		Iterator<Entry<String, String>> mapIterator = fileMap.entrySet().iterator();
		while (mapIterator.hasNext()) {
			Map.Entry<java.lang.String, java.lang.String> entry = (Map.Entry<java.lang.String, java.lang.String>) mapIterator.next();
			if (!((entry.getValue().contains(currentPrefix)) || (entry.getValue().contains(previousPrefix)))) {
				keyToDelete.add(entry.getKey());
			}
		}

		Iterator<String> iterator = keyToDelete.iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			TmpFileManager.removeTmpFile(key);
		}
	}

	private static String getCurrentHourPrefix() {
		Calendar calendar = GregorianCalendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		return PREFIX + "_" + hour + "_";
	}

	private static String getPreviousHourPrefix() {
		Calendar calendar = GregorianCalendar.getInstance();
		calendar.add(Calendar.HOUR_OF_DAY, -1);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		return PREFIX + "_" + hour + "_";
	}

	public static String getPathForFile(String fileName) {
		deleteOldEntries();
		return fileMap.get(fileName);
	}

	public static void add(FileItem item) throws Exception {
		FileOutputStream output = null;
		InputStream input = null;
		try {
			File tmpFile = File.createTempFile(getCurrentHourPrefix(), "");
			output = new FileOutputStream(tmpFile);
			input = item.getInputStream();
			IOUtils.copy(input, output);
			fileMap.put(item.getName(), tmpFile.getPath());
		} finally {
			if (input != null) {
				input.close();
			}
			if (output != null) {
				output.close();
			}
		}
	}

	public static byte[] getBytesForFile(String fileName) throws Exception {
		String pathForFile = getPathForFile(fileName);
		File aux = new File(pathForFile);
		if (aux.exists() == false) {
			return new byte[0];
		} else {
			return FileUtils.readFileToByteArray(aux);
		}
	}

}
